import * as THREE from 'three'
import { MTLLoader } from 'THREE/examples/jsm/loaders/MTLLoader'
import { OBJLoader } from 'THREE/examples/jsm/loaders/OBJLoader'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

let width = window.innerWidth
let height = window.innerHeight
let k = width / height
let Scene = new THREE.Scene()
let Camera = new THREE.PerspectiveCamera(75, k, 1, 1000) // 透视
Camera.position.set(200, 200, 200)
Camera.lookAt(Scene.position) // 设置相机的方向
let Renderer = new THREE.WebGLRenderer({
    antialias: true
})
Renderer.setSize(width, height) // 设置渲染区域
Renderer.setClearColor(0x323232, 1)
Renderer.shadowMap.enabled = true // 阴影效果
window.onresize = function () {
    Renderer.setSize(window.innerWidth, window.innerHeight) // 更新总宽高
    Camera.aspect = window.innerWidth / window.innerHeight // 更新观察宽高比
    Camera.updateProjectionMatrix() // 更新相机属性，需要手动更新相机
}

// 坐标格辅助
let gridhelper = new THREE.GridHelper(1000, 200, 0x888888, 0x273174)
Scene.add(gridhelper)
// 光源
let Point = new THREE.SpotLight(0x888888) // 聚光灯
Point.position.set(170, 50, 0)
Point.castShadow = true // 阴影效果
Scene.add(Point)
let directional_light = new THREE.DirectionalLight(0xffffff, 2) // 平行光
directional_light.position.set(400, 400, 400)
Scene.add(directional_light)
let Ambient = new THREE.AmbientLight(0xcccccc) // 环境光
Scene.add(Ambient)


// 加载 obj 模型
function loadOBJ(obj, mtl) {
    let obj_loader = new OBJLoader()
    let mtl_loader = new MTLLoader()

    mtl_loader.load(mtl, function(materials) {
        console.log(materials)
        obj_loader.setMaterials(materials)
        obj_loader.load(obj, function(obj_info) {
            console.log(obj_info)
            let scale = 0.006
            obj_info.scale.set(scale, scale, scale)
            obj_info.translateY(10)
            obj_info.translateX(100)
            Scene.add(obj_info)
            Point.lookAt(obj_info)
        })
    })
}
// loadOBJ('/static/ningbo/obj.obj', '/static/ningbo/obj.mtl')


// 
let clock = new THREE.Clock()
// 轨道控制器
let orbit_control = null
function control() {
    orbit_control = new OrbitControls(Camera, Renderer.domElement)
    orbit_control.target = new THREE.Vector3(0, 0, 0) // 控制焦点(目标)
    orbit_control.enableKeys = true
}
control()



function init() {
    Renderer.render(Scene, Camera)
    orbit_control.update(clock.getDelta())
    requestAnimationFrame(init)
}

init()


export {
    Renderer
}